import { defineStore } from 'pinia'

const useUserStore = defineStore('user', {
    state: () => ({
        userInfo: null,
        isLogin: true,
        num: 0
    }),

    getters: {
        // 检查token是否过期
        isTokenExpired: (state) => {
            if (!state.token || !state.tokenExpire) return true
            return Date.now() > state.tokenExpire * 1000
        },

        getToken: (state) => {
            state.num++
            // console.log("执行一次获取token", state.num);

            let token = JSON.parse(localStorage.getItem("mine_token") || '{}');
            if (token.v) {
                return JSON.parse(token.v)
            }
            return ""
        },
        getRefreshToken: () => {
            let refreshToken = JSON.parse(localStorage.getItem("mine_refresh_token") || '{}');
            if (refreshToken.v) {
                return JSON.parse(refreshToken.v)
            }
            return ""
        }
    },

    actions: {
        // 设置token信息
        setTokenInfo(tokenData) {
            let token = JSON.parse(localStorage.getItem("mine_token") || '{}');
            token.v = JSON.stringify(tokenData.access_token)
            token.c = Date.now()
            token.e = tokenData.expire_at ? Date.now() + (tokenData.expire_at * 1000) : 0
            localStorage.setItem("mine_token", JSON.stringify(token));

            let refreshToken = JSON.parse(localStorage.getItem("mine_refresh_token") || '{}');
            refreshToken.v = JSON.stringify(tokenData.refresh_token)
            refreshToken.c = Date.now()
            refreshToken.e = tokenData.expire_at ? Date.now() + (tokenData.expire_at * 1000) : 0
            localStorage.setItem("mine_refresh_token", JSON.stringify(refreshToken));
            this.isLogin = true
        },


        // 设置用户信息
        setUserInfo(userInfo) {
            this.userInfo = userInfo
        },

        // 登出
        logout() {
            // const fullUrl = window.location;
            // let goUrl = fullUrl.origin + fullUrl.pathname + "#/login?redirect=/"

            // 清除token
            localStorage.removeItem("mine_refresh_token")
            localStorage.removeItem("mine_token")
            this.userInfo = null
            this.isLogin = false
            // console.log(goUrl);
            window.location.href = 'https://gyh.admin.dev.yingzhu.net/admin/#/welcome';

        }
    },

    // 开启数据缓存
    persist: {
        storage: localStorage,
        key: 'user',
        paths: ['token', 'refreshToken', 'userInfo', 'isLogin', 'tokenExpire']
    }
})

export default useUserStore 